module.exports = function(app) {

    var mysqlUtil = require('../app/util/mysqlUtil');
    var md5 = require('../app/util/md5');
    //var sha256 = require('../app/util/sha256');

    app.get('/login', function(req, res) {
        res.render('login/index');
    });

    app.post('/doLogin', function(req, res) {
        var username = req.body.username;
        var password = req.body.password;

        authenticate(username, password, function(user) {
            if (user) {
                req.session.user = user;
                res.redirect('/home');
            } else {
                req.session.error = '账号或密码有误！';
                res.redirect('/login');
            }
        });
    });

    app.get('/logout', function(req, res) {
        if (req.session.user)
            req.session.user = undefined;
        res.redirect('/login');
    });


    /**
     * 验证账号密码
     */
    function authenticate(name, pass, fn) {
        var _pass = md5(pass || '');
        mysqlUtil.exec('select * from t_user where code=? and password=?', [name, _pass], function(err, result) {
            if (result.length == 0) {
                return fn();
            } else {
                var user = result[0];
                return fn(user);
            }
        });

        /*var user = {
            username : 'admin',
            password : '1'
        }
        if (user.username === name && user.password === pass) {
            return fn(user)
        } else {
            return fn();
        }*/
    };
}
